/*!
 * Page: pages/activity/search/Search
 * License: MIT
 * Created: 2019-12-12 15:59
 */

import { activityApi } from '/api/activity'
import { $utils, $event } from '/utils'

Page({
  data: {
    list: [] as Activity[],
    isLastPage: false,
    keyword: '',
    isSearch: false,
    wantJoin: false,
  },
  onShow() {
    $event.on('activityChange', this, () => {
      this.setData({
        list: [],
        isLastPage: false,
      })
      this.onLoadmore()
    })
  },
  async join(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { item, index },
      },
    } = e
    if (this.data.wantJoin || item.wantJoin) {
      wx.showToast({
        title: '您已加入过了哟',
        icon: 'none',
        duration: 1000,
      })
      return
    }
    this.setData({
      wantJoin: true,
    })
    await activityApi.wantJoinActivity(+item.id)
    const list = this.data.list
    list[index].wantJoin = true
    this.setData({
      list,
      wantJoin: false,
    })
    wx.showToast({
      title: '加入成功',
      icon: 'none',
      duration: 1000,
    })
  },
  onPullDownRefresh() {
    this.setData({
      list: [],
      isLastPage: false,
    })
    this.onLoadmore()
  },

  onReachBottom() {
    this.onLoadmore()
  },
  /** 搜索 */
  search(e: WechatMiniprogram.CustomEvent) {
    const {
      detail: { value },
    } = e
    this.setData({
      list: [],
      isLastPage: false,
      keyword: value,
    })
    this.onLoadmore()
  },
  /**获取列表 */
  async onLoadmore() {
    if (this.data.isLastPage) {
      wx.showToast({
        title: '已没有更多了',
        icon: 'none',
        duration: 1000,
      })
      return
    }
    wx.showLoading({
      title: '加载中',
    })
    const offset = this.data.list ? $utils.getLastField(this.data.list) : ''
    const list = await activityApi.getActivityList({
      c: '',
      area: '',
      offset,
      limit: 20,
      keyword: this.data.keyword,
    })
    const isLastPage = list.length < 20
    this.setData({
      list: [...this.data.list, ...list],
      isLastPage,
      isSearch: true,
    })
    wx.stopPullDownRefresh()
    wx.hideLoading()
  },
  /** 活动详情 */
  todetail(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { id },
      },
    } = e
    wx.navigateTo({
      url: `/pages/activity/detail/detail?id=${id}`,
    })
  },
})
